package com.resou.reader.mine.login;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TextInputEditText;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.resou.reader.R;
import com.resou.reader.ReSouApplication;
import com.resou.reader.api.entry.LoginData;
import com.resou.reader.assist.WebActivity;
import com.resou.reader.base.ResouBaseActivity;
import com.resou.reader.utils.ErrorUtils;
import com.resou.reader.utils.NetworkUtils;
import com.resou.reader.utils.PreferenceUtil;
import com.resou.reader.utils.ToastUtil;
import com.resou.reader.utils.WXUtils;
import com.resou.reader.view.Loading;
import com.umeng.analytics.MobclickAgent;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;

import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * 登录页面
 */
public class LoginActivity extends ResouBaseActivity<LoginPresenter> implements ILoginContact.ILoginView {
    public static void start(Context context) {
        Intent starter = new Intent(context, LoginActivity.class);
        context.startActivity(starter);
    }

    @BindView(R.id.ivBack)
    ImageView ivBack;
    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.mTitleBar)
    RelativeLayout mTitleBar;
    @BindView(R.id.ivIcon)
    ImageView ivIcon;
    @BindView(R.id.etPhone)
    TextInputEditText etPhone;
    @BindView(R.id.ivClear)
    ImageView ivClear;
    @BindView(R.id.ivIcon2)
    ImageView ivIcon2;
    @BindView(R.id.etPwd)
    TextInputEditText etPwd;
    @BindView(R.id.tvSend)
    TextView tvSend;
    @BindView(R.id.tvLogin)
    TextView tvLogin;
    @BindView(R.id.llOther)
    LinearLayout llOther;
    @BindView(R.id.tvAgreement)
    TextView tvAgreement;
    @BindView(R.id.tvPrivacy)
    TextView tvPrivacy;
    @BindView(R.id.ivWeixin)
    ImageView ivWeixin;
    @BindView(R.id.ivQQ)
    ImageView ivQQ;
    @BindView(R.id.llQQ)
    LinearLayout llQQ;
    @BindView(R.id.llWX)
    LinearLayout llWX;
    @BindView(R.id.ivRecentLogin)
    ImageView ivRecentLogin;
    @BindView(R.id.ivRecentLogin1)
    ImageView ivRecentLogin1;


    Unbinder unbinder;
    View contentView;
    String loginType = "2";//默认微信登录
    String unionid = "";
    String gender = "";
    String name = "";
    String openId = "";
    String icon = "";
    String city = "";
    String sex = "";
    boolean isFinished = true;
    boolean isQQInstall;
    boolean isWXInstall;

    @Override
    protected void initStatusBar() {

    }

    @Override
    protected void initPresenter() {
        mPresenter = new LoginPresenter(this);
    }

    @Override
    protected void initView() {
        isQQInstall = WXUtils.isQQClientAvailable(this);
        isWXInstall = WXUtils.isWeixinAvilible(this);
        etPhone.addTextChangedListener(textWatcher);
        etPwd.addTextChangedListener(textWatcher);
        setLoginBtnState();
        if (PreferenceUtil.getInstance(ReSouApplication.getRSApplication()).getLoginState() == 1) {
            ivRecentLogin.setVisibility(View.VISIBLE);
            ivRecentLogin1.setVisibility(View.INVISIBLE);
        } else if (PreferenceUtil.getInstance(ReSouApplication.getRSApplication()).getLoginState() == 2) {
            ivRecentLogin.setVisibility(View.INVISIBLE);
            ivRecentLogin1.setVisibility(View.VISIBLE);
        } else {
            ivRecentLogin.setVisibility(View.INVISIBLE);
            ivRecentLogin1.setVisibility(View.INVISIBLE);
        }
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    public void retryRefreshData() {

    }

    @Override
    public void initData() {
        if (!isQQInstall) {
            llQQ.setVisibility(View.GONE);
        }
        if (!isWXInstall) {
            llWX.setVisibility(View.GONE);
        }
        if (!isWXInstall && !isQQInstall) {
            llOther.setVisibility(View.GONE);
        }
    }

    @Override
    public void showContent() {

    }

    @Override
    public void showProgress() {
    }

    @Override
    public void showError(Throwable throwable) {
        ToastUtil.makeShortToast(throwable.getMessage());
    }

    @Override
    public void showEmpty() {

    }

    @OnClick({R.id.ivBack, R.id.ivClear, R.id.tvSend, R.id.tvAgreement, R.id.tvPrivacy, R.id.ivWeixin, R.id.ivQQ, R.id.tvLogin})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ivBack:
                finish();
                break;
            case R.id.ivClear:
                if (etPhone != null)
                    etPhone.setText("");
                break;
            case R.id.tvSend:
                if (NetworkUtils.isNetworkConnected(this)) {
                    mPresenter.sendSMS(etPhone.getText().toString());
                    isFinished = false;
                } else {
                    ToastUtil.makeShortToast("网络异常");
                }
                break;

            case R.id.tvLogin:
                if (NetworkUtils.isNetworkConnected(this)) {
                    showLoading();
                    mPresenter.mergeAccount(0, etPhone.getText().toString(), null);
                } else {
                    ToastUtil.makeShortToast("网络异常");
                }
                break;
            /**
             * 用户协议
             */
            case R.id.tvAgreement:
                WebActivity.startActivity(this, "https://m.resouxs.com/login/protocol?app=app", "用户协议");
                break;
            /**
             * 用户隐私
             */
            case R.id.tvPrivacy:
                WebActivity.startActivity(this, "https://m.resouxs.com/login/privacy?app=app", "隐私协议");
                break;
            case R.id.ivWeixin:
                if (NetworkUtils.isNetworkConnected(this)) {
                    if (!isWXInstall) {
                        Toast.makeText(this, "微信未安装", Toast.LENGTH_SHORT).show();
                    } else {
                        showLoading();
                        thirdPartyLogin(SHARE_MEDIA.WEIXIN);
                        dismiss();
                    }
                } else {
                    ToastUtil.makeShortToast("网络异常");
                }

                break;
            case R.id.ivQQ:
                if (NetworkUtils.isNetworkConnected(this)) {
                    if (!isQQInstall) {
                        Toast.makeText(this, "QQ未安装", Toast.LENGTH_SHORT).show();
                    } else {
                        showLoading();
                        thirdPartyLogin(SHARE_MEDIA.QQ);
                        dismiss();
                    }
                } else {
                    ToastUtil.makeShortToast("网络异常");
                }

                break;
        }
    }

    @Override
    public void toastMsg(String msg) {
        if (msg.equals("验证码发送失败！")) {
            ToastUtil.makeShortToast(ReSouApplication.getRSApplication().getString(R.string.user_phone_number_ill));
        } else {
            ToastUtil.makeShortToast(msg);
        }
    }

    @Override
    public void updateVerifyText(String text, boolean isFinished) {
        this.isFinished = isFinished;
        tvSend.setClickable(isFinished);
        if (isFinished) {
            mPresenter.onViewDismiss();
            tvSend.setText("获取验证码");
            tvSend.setAlpha(1f);
            tvSend.setClickable(true);
        } else {
            tvSend.setText(text);
            tvSend.setAlpha(0.5f);
            tvSend.setClickable(false);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("LoginActivity");
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
        MobclickAgent.onPageEnd("LoginActivity");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mPresenter != null) {
            mPresenter.onViewDismiss();
        }
        UMShareAPI.get(this).release();
    }

    @Override
    public void dismiss() {
        clearData();
        mPresenter.onViewDismiss();
    }

    @Override
    public void hideProgress() {
        dissLoading();
    }

    @Override
    public void phoneLogin() {
        mPresenter.smsLogin(etPhone.getText().toString(), etPwd.getText().toString());
        PreferenceUtil.getInstance(ReSouApplication.getRSApplication()).saveLoginState(0);
    }

    @Override
    public void winXinLogin(SHARE_MEDIA platform) {
        mPresenter.login(platform, loginType, unionid, sex, name, icon);
        PreferenceUtil.getInstance(ReSouApplication.getRSApplication()).saveLoginState(1);


    }

    @Override
    public void qqLogin(SHARE_MEDIA platform) {
        mPresenter.login(platform, loginType, unionid, sex, name, icon);
        PreferenceUtil.getInstance(ReSouApplication.getRSApplication()).saveLoginState(2);
    }

    @Override
    public void loginSuccess(LoginData loginData) {
        ToastUtil.makeShortToast("登录成功");
        finish();
    }

    private void clearData() {
        try {
            if (etPwd != null)
                etPwd.setText("");
            if (etPhone != null)
                etPhone.setText("");
            updateVerifyText(ReSouApplication.getRSApplication().getString(R.string.user_login_get_code), true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 更新登录与发送验证码的状态
     */
    private void setLoginBtnState() {
        boolean clickable = !TextUtils.isEmpty(etPhone.getText()) && etPhone.getText().toString().length() == 11 &&
                !TextUtils.isEmpty(etPwd.getText()) && etPwd.getText().toString().length() == 6;
//        tvLogin.setPressed(!clickable);
        Log.i("状态", "setLoginBtnState: " + clickable);
        if (clickable) {
            tvLogin.setClickable(clickable);
            tvLogin.setAlpha(1f);
        } else {
            tvLogin.setClickable(clickable);
            tvLogin.setAlpha(0.5f);
        }
        if (!TextUtils.isEmpty(etPhone.getText()) && etPhone.getText().toString().length() == 11) {
            if (isFinished) {
                tvSend.setAlpha(1f);
                tvSend.setClickable(true);
            }
        } else {
            tvSend.setAlpha(0.5f);
            tvSend.setClickable(false);
        }
        if (etPhone.getText().toString().length() > 0) {
            ivClear.setVisibility(View.VISIBLE);
        } else {
            ivClear.setVisibility(View.VISIBLE);
        }
    }

    private TextWatcher textWatcher = new TextWatcher() {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            setLoginBtnState();
        }

        @Override
        public void afterTextChanged(Editable s) {
        }
    };

    /**
     * 微信登录
     * QQ登录
     */

    private UMAuthListener authListener = new UMAuthListener() {

        /**
         * @desc 授权开始的回调
         * @param platform 平台名称
         */
        @Override
        public void onStart(SHARE_MEDIA platform) {
        }

        /**
         * @desc 授权成功的回调
         * @param platform 平台名称
         * @param action 行为序号，开发者用不上
         * @param data 用户资料返回
         */
        @Override
        public void onComplete(final SHARE_MEDIA platform, int action, Map<String, String> data) {
            unionid = data.get("unionid");//用户唯一标识
            openId = data.get("openid");
            name = data.get("screen_name");//用户昵称
            gender = data.get("gender");//用户性别
            icon = data.get("profile_image_url");//用户头像
            city = data.get("city");//
            sex = "1";
            loginType = "2";
            if ("女".equalsIgnoreCase(gender)) {
                sex = "2";
            }

            if (platform == SHARE_MEDIA.QQ) {
                loginType = "3";
            }

            Loading.getInstance().setLoadingText("登录中...");
            if (loginType.equals("2")) {
                mPresenter.mergeAccount(1, unionid, null);
            } else {
                mPresenter.mergeAccount(2, unionid, null);
            }
        }

        /**
         * @desc 授权失败的回调
         * @param platform 平台名称
         * @param action 行为序号，开发者用不上
         * @param throwable 错误原因
         */
        @Override
        public void onError(SHARE_MEDIA platform, int action, Throwable throwable) {
//            ErrorUtils.showError(throwable);
            dissLoading();
            ToastUtil.makeShortToast(throwable.getMessage());
        }

        /**
         * @desc 授权取消的回调
         * @param platform 平台名称
         * @param action 行为序号，开发者用不上
         */
        @Override
        public void onCancel(SHARE_MEDIA platform, int action) {
            dissLoading();
        }
    };

    /**
     * 第三方登录
     *
     * @param platform
     */
    private void thirdPartyLogin(SHARE_MEDIA platform) {
        UMShareAPI.get(this).getPlatformInfo(this, platform, authListener);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }
}
